﻿using System;

namespace SpLocalizer.Common.Patterns
{
    /// <summary>
    /// Represent singleton pattern
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class Singleton<T> where T : class
    {
        private readonly Func<T> _creator;
        private T _value;

        public Singleton(Func<T> creator)
        {
            _value = default(T);
            _creator = creator;
        }

        public T Value
        {
            get
            {
                if (_value == null)
                {
                    lock (_creator)
                    {
                        if (_value == null)
                        {
                            _value = _creator();
                        }
                    }
                }

                return _value;
            }
        }

        public void Clear()
        {
            if (_value != null)
            {
                lock (_creator)
                {
                    if (_value != null)
                    {
                        var disposable = _value as IDisposable;

                        if (disposable != null)
                            disposable.Dispose();

                        _value = null;
                    }
                }
            }
        }
    }
}